<template> 
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="primary" size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px;float: right;padding: 10px 40px;">添加</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="roleTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="角色名称" align="center">
          <template slot-scope="scope">{{ scope.row.group_title }}</template>
        </el-table-column>
        <el-table-column label="是否启用" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.group_status">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-row>
              <!-- <el-button size="mini"
                          type="text"
                          @click="handleSelectMenu(scope.$index, scope.row)">分配菜单
               </el-button>-->
              <!--  <el-button size="mini"
                           type="text"
                           @click="handleSelectResource(scope.$index, scope.row)">分配资源
                </el-button>-->
            </el-row>
            <el-row>
              <el-button size="mini"
                         type="text"
                         @click="handleUpdate(scope.$index, scope.row)">
                编辑
              </el-button>
              <el-button size="mini"
                         type="text"
                         @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container" style="text-align: center;margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.page"
        :page-size="listQuery.page_size"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑角色':'添加角色'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="role"
               :rules="rules"
               ref="roleForm"
               label-width="150px" size="small">
        <el-form-item label="角色名称：" prop="group_title">
          <el-input v-model="role.group_title" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="分配菜单：">
          <el-tree
            :data="menuData"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            highlight-current
            @check="queryNode"
            :props="defaultProps">
          </el-tree>
        </el-form-item>
        <!-- <el-form-item label="是否启用：">
           <el-radio-group v-model="role.status">
             <el-radio :label="1">是</el-radio>
             <el-radio :label="0">否</el-radio>
           </el-radio-group>
         </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm('roleForm')" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  groupAdd, groupList, groupAjax, groupLine, groupEdit, groupDel
} from '@/api/role';
import {formatDate} from '@/utils/date';
import {menuList} from "@/api/menu";

const defaultListQuery = {
  page: 1,
  page_size: 10
};
const defaultRole = {
  group_title: '',
  group_rules: 0,
};
export default {
  name: 'roleList',
  data() {
    return {
      typeId: 'a',
      id: null,
      roleID: null,
      defaultProps: {
        children: 'children',
        label: 'rule_name'
      },
      menuData: [],
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      role: Object.assign({}, defaultRole),
      isEdit: false,
      rules: {
        group_title: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getList();
    this.getMenuList();
  },
  filters: {
    formatDateTime(time) {
      if ( time == null || time === '' ) {
        return 'N/A';
      }
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    }
  },
  methods: {
    /**
     * 查询列表每条数据的详情
     */
    handleUpdate(index, row) {
      this.id = row.id;
      this.dialogVisible = true;
      this.isEdit = true;
      this.listLoading = true;
      groupLine(row.id).then(response => {
        this.listLoading = false;
        console.log(response);
        this.role.group_title = response.data.group_title;
        this.role.group_rules = response.data.group_rules;
        let that = this
        that.$refs.tree.setCheckedKeys([])
        if ( response.data.group_rules == 'all' ) {
          that.$refs.tree.setCheckedNodes(that.menuData);
        }
        setTimeout(function () {
          if ( response.data.group_rules != 'all' ) {
            response.data.group_rules.forEach(value => {
              that.$refs.tree.setChecked(value, true, false);
            });
          }
        }, 200);
      });
    },
    /**
     * 获取列表数据
     */
    getList() {
      this.listLoading = true;
      groupList(this.listQuery).then(response => {
        this.listLoading = false;
        console.log(response);
        this.list = response.data.data_list;
        this.total = response.data.total;
      });
    },

    /**
     * 获取树型控制的值
     * @param a
     * @param b
     */
    queryNode(a, b) {
      this.roleID = b.checkedKeys.concat(b.halfCheckedKeys)
      this.role = {group_title: this.role.group_title, group_rules: this.roleID};
    },
    /**
     * 获取菜单栏列表数据
     */
    getMenuList() {
      this.listLoading = true;
      menuList().then(response => {
        this.listLoading = false;
        console.log(response);
        this.menuData = response.data.list
      });
    },
    /* handleResetSearch() {
       this.listQuery = Object.assign({}, defaultListQuery);
     },*/
    /* handleSearchList() {
       this.listQuery.pageNum = 1;
       this.getList();
     },*/
    handleSizeChange(val) {
      this.listQuery.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
    },
    /**
     * 修改列表中的状态
     * @param index
     * @param row
     */
    handleStatusChange(index, row) {
      this.$confirm('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        groupAjax(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
        this.getList();
      });
    },
    /**
     * 删除
     * @param index
     * @param row
     */
    handleDelete(index, row) {
      this.$confirm('是否要删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        groupDel(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        });
      }).catch(e => e);
    },
    /**
     * 新增/修改
     * @param formName
     */
    handleDialogConfirm(formName) {
      this.$refs[ formName ].validate((valid) => {
        if ( valid ) {
          this.$confirm('是否要确认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if ( this.isEdit ) {
              groupEdit({
                id: this.id,
                group_title: this.role.group_title,
                group_rules: this.role.group_rules
              }).then(response => {
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
              })
            } else {
              groupAdd(this.role).then(response => {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
              })
            }
          })
        }
      });
    },
    handleSelectMenu(index, row) {
      this.$router.push({path: '/ums/allocMenu', query: {roleId: row.id}})
    },
    handleSelectResource(index, row) {
      this.$router.push({path: '/ums/allocResource', query: {roleId: row.id}})
    }
  }
}
</script>
<style></style>


